package com.forum.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.forum.annotation.IgnoreAuth;
import com.forum.entity.StudentinfotabEntity;
import com.forum.service.StudentinfotabService;
import com.forum.service.TokenService;
import com.forum.utils.MPUtil;
import com.forum.utils.PageUtils;
import com.forum.utils.R;
import com.forum.utils.ValidatorUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;

/**
 * <p>
 * 学生信息表 前端控制器
 * </p>
 *
 * @author 张继成
 * @since 2023-12-30
 */
@RestController
@RequestMapping("/Student")
@Slf4j
@Api(tags = "学生角色控制")
public class StudentinfotabController {
    @Autowired
    private StudentinfotabService studentInfoService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private TokenService tokenService;


    @GetMapping("/list")
    @ApiOperation(value = "获取全体学生列表",notes = "")
    @SuppressWarnings("unchecked")
    public R list(StudentinfotabEntity studentinfoEntity){
        EntityWrapper<StudentinfotabEntity> StudentinfoEntityQueryWrapper = new EntityWrapper<StudentinfotabEntity>();
        StudentinfoEntityQueryWrapper.allEq(MPUtil.allEQMapPre(studentinfoEntity,"studentinfoEntity"));
        return R.ok().put("data" , studentInfoService.selectListView(StudentinfoEntityQueryWrapper));
    }

    /**
     *@Author zhangjc2
     *
     *@Description // 登录逻辑
     *@Date 2023-12-01 22:18
     * @param password
     * @param PhoneNum
     * @param PhoneCode
     * @return com.forum.utils.R
     **/
    @IgnoreAuth
    @RequestMapping("/login")
    public R login(String studentname,String password, String PhoneNum, Integer PhoneCode) {
        Integer CodeInRedis = (Integer) redisTemplate.opsForValue().get(PhoneNum);
        if (CodeInRedis !=null && CodeInRedis.equals(PhoneCode)) {
            StudentinfotabEntity StudentEntity = studentInfoService.
                    selectOne(new EntityWrapper<StudentinfotabEntity>().eq("Phone", PhoneNum));
            if (StudentEntity == null) {
                return R.error("账号不存在！");
            }
            //开发过程使用
            String studentPassword = StudentEntity.getStudentpassword();
            String studentName = StudentEntity.getStudentname();
            log.info("当前用户账号为:{}"+"当前用户密码为:{}",studentPassword,studentName);
            //
            if (!StudentEntity.getStudentpassword().equals(password)
                || !StudentEntity.getStudentaccount().equals(studentname)) {
                return R.error("用户名或者密码错误！");
            }
            if (!"是".equals(StudentEntity.getToexmine())) {
                return R.error("账号状态异常，请联系管理员");
            }
            // 获取学生的token信息
            String token = tokenService.
                    generateToken(StudentEntity.getId(), StudentEntity.getStudentname(), "studentinfotab", "学生");
            return R.ok().put("token", token);
        } else {
            return R.error("验证码输入不正确请再次尝试");
        }
    }
    /**
     * 注册
     */
    @IgnoreAuth
    @PostMapping("/register")
    public R register(@RequestBody StudentinfotabEntity xuesheng){
        //ValidatorUtils.validateEntity(xuesheng);
        StudentinfotabEntity u = studentInfoService.selectOne(new EntityWrapper<StudentinfotabEntity>().eq("StudentAccount", xuesheng.getStudentaccount()));
        if(u!=null) {
            return R.error("注册用户已存在");
        }
        Long uId = new Date().getTime();
        xuesheng.setId(uId);
        log.info("本次需要插入的实体数据：{}",xuesheng);
        studentInfoService.insert(xuesheng);
        return R.ok();
    }

    /**
     * 获取当前用户的sesion
     */
    @GetMapping("/session")
    public R getCurUser(HttpServletRequest request){
        Long id= (Long)request.getSession().getAttribute("userId");
        StudentinfotabEntity studentinfotabEntity = studentInfoService.selectById(id);
        return R.ok().put("data",studentinfotabEntity);
    }

    @GetMapping("/page")
    @SuppressWarnings("unchecked")
    public R page(@RequestParam Map<String,Object> params,StudentinfotabEntity stuEntiy){
        EntityWrapper<StudentinfotabEntity> ew = new EntityWrapper<>();
        PageUtils pageUtils = studentInfoService.queryPage(params, MPUtil.sort(MPUtil.between(MPUtil.likeOrEq(ew, stuEntiy), params), params));
        return R.ok().put("data",pageUtils);
    }

    @PostMapping("/update")
    @Transactional
    public R update(@RequestBody StudentinfotabEntity xuesheng, HttpServletRequest request){
        ValidatorUtils.validateEntity(xuesheng);
        studentInfoService.updateById(xuesheng);//全部更新
        return R.ok();
    }

    @GetMapping("/info/{id}")
    public R info(@PathVariable("id") Long id){
        StudentinfotabEntity xuesheng = studentInfoService.selectById(id);
        return R.ok().put("data", xuesheng);
    }

    @PostMapping("/delete")
    public R delete(@RequestBody Long[] ids){
        studentInfoService.deleteBatchIds(Arrays.asList(ids));
        return R.ok();
    }
}
